package com.moss.cloud.base.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moss.cloud.base.api.model.from.BatchBaseFrom;
import com.moss.cloud.base.biz.mapper.SysRoleMenuMapper;
import com.moss.cloud.base.biz.service.ISysRoleMenuService;
import com.moss.cloud.common.base.model.po.SysRoleMenu;
import com.moss.cloud.common.core.enums.state.Deleted;
import com.moss.cloud.common.core.utils.BooleanHandel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色菜单业务实现
 *
 * @author 瑾年
 * @date 2023年4月16日
 */
@Slf4j
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    /**
     * 查询角色菜单列表
     *
     * @param roleIds
     * @return
     */
    @Override
    public List<SysRoleMenu> roleMenus(List<Long> roleIds) {
        return this.list(new QueryWrapper<SysRoleMenu>().lambda()
                .in(SysRoleMenu::getRoleId, roleIds).notIn(SysRoleMenu::getDeleted, Deleted.DELETE.code()));
    }

    /**
     * 查询角色菜单列表返回菜单id集合
     *
     * @param roleIds
     * @return
     */
    @Override
    public List<Long> roleMenuIds(List<Long> roleIds) {
        List<SysRoleMenu> sysRoleMenus = this.roleMenus(roleIds);
        return CollectionUtils.isNotEmpty(sysRoleMenus) ?
                sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList()) :
                Collections.emptyList();
    }

    /**
     * 查询角色的菜单集合
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Long> roleMenuIds(Long roleId) {
        List<Long> ids = new ArrayList<>();
        ids.add(roleId);
        return this.roleMenuIds(ids);
    }

    /**
     * 角色批量授权菜单
     *
     * @param batchBaseFrom
     * @return
     */
    @Override
    public Boolean roleAuthMenus(BatchBaseFrom batchBaseFrom) {
        List<SysRoleMenu> sysRoleMenus = this.list(new QueryWrapper<SysRoleMenu>().lambda()
                .eq(SysRoleMenu::getRoleId, batchBaseFrom.getRoleId()));
        BooleanHandel.isTrue(CollectionUtils.isNotEmpty(sysRoleMenus)).trueHandle(() -> {
            log.info("先删除该角色对应的菜单，再保存数据");
            this.remove(new QueryWrapper<SysRoleMenu>().lambda().eq(SysRoleMenu::getRoleId, batchBaseFrom.getRoleId()));
        });
        List<SysRoleMenu> roleMenus = batchBaseFrom.getIds().stream().map(item -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(item);
            sysRoleMenu.setRoleId(batchBaseFrom.getRoleId());
            return sysRoleMenu;
        }).collect(Collectors.toList());
        return this.saveBatch(roleMenus);
    }
}
